import { store } from '@/store';
import { defineStore } from 'pinia';

interface TabsState {
    count: number;
    currentMenu: any;
    tabsList: any[];
    menu: any[];
    keepAliveList: any[];
}

export const useTabsStore = defineStore({
    id: 'app-tabs',
    state: (): TabsState => ({
        count: 0,
        //当前菜单
        currentMenu: null,
        //标签页列表
        tabsList: [],
        menu: [],
        keepAliveList: ["Index"]
    }),
    getters: {
        getCurrentMenu(): any {
            return this.currentMenu;
        },
        getTabsList(): any {
            return this.tabsList;
        }
    },
    actions: {

        /**
         * 设置标签列表
         * @param tabsList
         */
        setTabsList(tabsList: any[]) {
            this.tabsList = tabsList;
        },

        /**
         * 选择菜单
         * @param val
         */
        selectMenu(val: any) {
            if (val.path === "/") {
                // state.currentMenu = null;
            } else {
                // state.currentMenu = val.name;
                let result = this.tabsList.findIndex(
                    (item: any) => item.name === { ...val }.name
                );
                if (result === -1) {
                    this.tabsList.push({ ...val });
                }
            }
        },

        /**
         * 关闭标签页
         * @param val
         */
        closeTab(val: any) {
            let result = this.tabsList.findIndex(
                (item) => item.name === val.name
            );
            this.tabsList.splice(result, 1);
            this.keepAliveList.length = 0;
            this.tabsList.forEach((item) => {
                this.keepAliveList.push(item.name);
            });
        },

        /**
         * 更新缓存列表
         * @param val
         */
        updateKeepList(val: any) {
            let index = this.keepAliveList.findIndex(
                (item: any) => item.name === val.name
            );
            if (index === -1) {
                this.keepAliveList.push(val.name);
            }
        },
    },
})

// Need to be used outside the setup
export function useTabsStoreWithOut() {
    return useTabsStore(store);
}
